
*********************************************************************
** This piece of code expects to find in the working directory
*a) the 100 files with simulated probabilities for each of the ESS respondents
*b) the DB_Minimal.dta file, which is a subset of columns of the main ACS dataset
*c) F&O_twodigits_Wide.dta, which contains the Frey and Osborne automation scores

use DB_Minimal.dta,replace


******************************************************************
* Creating simulated vulnerabilities and running the regressions *
******************************************************************


cap postclose Beta_Tilde

postfile Beta_Tilde beta sigma model_num using Estimates_Sim_All, every(1) replace


forvalues j=1/100 {

	display `j'

	
	** Load the simulated probabilities
	
	use sim`j',replace 
	
	gen i=1
	
	** Combine them with the F&O automatability scores
	
	joinby i using F&O_twodigits_Wide.dta, unmatched(master)

	drop _merge
	
	* Filling the gap for 10 and 70 for F&O 

	gen prob_robotized2d10=.2289381
	gen prob_robotized2d70=.62714636

	local codes "10 11 12 13 21 22 23 24 31 32 33 34 41 42 51 52 61 71 72 73 74 81 82 83 91 92 93"

		foreach code of local codes {

			gen threat_FO`code' = p`code'*prob_robotized2d`code'

		} 

	egen threat_FO=rowtotal(threat_FO10-threat_FO93), missing
	
	save Vulnerabilities_Sim`j'.dta,replace

	use DB_Minimal.dta,replace
	
	* Loading the j-th simulated probabilities of occupation
	
	joinby id using Vulnerabilities_Sim`j'.dta, unmatched(master)
	
	drop _merge
	
	* Creating the shock variables and the instruments:
	
	gen d13_indshock_fo=threat_FO*d13_perc_natrob 

	gen iv_d13_indshock_fo=threat_FO*iv_mean_d13_perc_natrob 

	* Standardizing the shock variables:

		local vars "d13_indshock_fo  iv_d13_indshock_fo"

		foreach x of local vars  {

			egen `x'_std=std(`x')
		}

	* Estimating the voting regressions
	

	ivreg2 radical_right CY* NU* eduyrs age female (d13_indshock_fo_std=iv_d13_indshock_fo_std)[pweight=pspwght], cluster(nuts2_year) partial(CY* NU*)

	* Storing the estimates
	
	mat betahat=e(b)

	mat se2=e(V)

	local b=betahat[1,1]

	local bse=se2[1,1]

	local bse=`bse'^.5
	
	display `b'

	display `bse'

	post Beta_Tilde  (`b') (`bse') (1)



	erase Vulnerabilities_Sim`j'.dta

}

postclose Beta_Tilde



** Load the 100 estimates of the main coefficient in the voting model, and obtain point estimates from these

use Estimates_Sim_All.dta, replace



scalar M=100


		egen betahat=mean(beta)

		gen V=sigma^2

		egen mean_V=mean(V)

		gen dev_sq= (beta-betahat)^2

		egen sum_dev=sum(dev_sq)

		gen standerr= (mean_V + (1+1/M)*(1/(M-1))*sum_dev)^.5



	
**** The estimates to be reported are the following

keep betahat standerr

keep if _n==1